import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Product, ProductService, Comment } from "../shared/product.service";
import { WebSocketService } from "../shared/web-socket.service";
import { Subscription } from "rxjs";

@Component ({
    selector : 'app-producr-details',
    templateUrl : './producr-details.component.html',
    styleUrls : ['./producr-details.component.css']
})
export class ProducrDetailsComponent implements OnInit {

    //private productTitle : string;
    product : Product;
    comments : Comment[];
    newRating : number = 4;
    newComment : string = '';
    isCommentHide : boolean = true;
    isWatched : boolean = false;
    currentBid : number;
    subscription : Subscription;

    constructor ( private routeInfo : ActivatedRoute,
                  private productService : ProductService,
                  private wsService : WebSocketService ) {
    }

    ngOnInit () {
        let productId : number = this.routeInfo.snapshot.params['productId'];
        this.productService.getProduct (productId).subscribe (
            prod => {
                this.product = prod;
                this.currentBid = prod.price;
            });
        this.productService.getCommentsForProduct (productId).subscribe (
            com => this.comments = com
        );
        //this.productTitle = this.routeInfo.snapshot.params['productTitle']
    }

    addComment () {
        let commnetAll = new Comment (0, this.product.id, new Date ().toISOString (), this.newRating, '用户+++++名', this.newComment);
        this.comments.unshift (commnetAll);
        let sum = this.comments.reduce (( sum, comment ) => sum + comment.rating, 0);
        this.product.rating = sum / this.comments.length;
        this.newRating = 4;
        this.newComment = '';
        this.isCommentHide = true;
    }

    watchProduct () {
        if(this.subscription){
            this.subscription.unsubscribe();
            this.isWatched = false;
            this.subscription = null;
        }
        else {
            this.isWatched = true;
            this.subscription = this.wsService.createObservableSocket ('ws://localhost:9090', this.product.id)
                .subscribe (
                    products => {
                        console.info('products',products);
                        let prod = products.find (p => p.productId === this.product.id);
                        this.currentBid = prod.bid;
                    }
                );
        }
    }




}
